<template>
  <div class="exam-papers">
    <el-card class="page-card">
      <template #header>
        <div class="card-header">
          <span>试卷管理</span>
          <el-button type="primary" @click="handleCreatePaper">新建试卷</el-button>
        </div>
      </template>
      
      <data-table
        ref="dataTableRef"
        :api="getExamPapers"
        :columns="columns"
      >
        <template #operation="{ row }">
          <el-button link type="primary" @click="handleEdit(row)">编辑</el-button>
          <el-button link type="primary" @click="handlePreview(row)">预览</el-button>
          <el-button link type="danger" @click="handleDelete(row)">删除</el-button>
        </template>
      </data-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import DataTable from '../../components/common/DataTable.vue'
import { examService } from '../../services/exam'
import { useRouter } from 'vue-router'

const router = useRouter()
const dataTableRef = ref(null)

const columns = [
  { label: '试卷名称', prop: 'name' },
  { label: '科目', prop: 'subject' },
  { label: '题目数量', prop: 'questionCount' },
  { label: '创建时间', prop: 'createTime' },
  { label: '操作', slot: 'operation', width: 200, fixed: 'right' }
]

const handleCreatePaper = () => {
  router.push('/exam/paper/create')
}

const handleEdit = (row) => {
  router.push(`/exam/paper/edit/${row.id}`)
}

const handlePreview = (row) => {
  router.push(`/exam/paper/preview/${row.id}`)
}

const getExamPapers = (params) => {
  return examService.getExamPapers(params.page, params.pageSize)
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除这份试卷吗？', '提示', {
      type: 'warning'
    })
    await examService.deleteExamPaper(row.id)
    ElMessage.success('删除成功')
    dataTableRef.value?.refresh()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
